package middleware

import (
	"app/pkg/e"
	"app/pkg/jwt"
	"app/serializer"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

// JWT token验证中间件
func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		code := e.SUCCESS
		token := c.GetHeader("Authorization")
		if token == "" {
			code = e.ErrorTokenCheck
		} else {
			claims, err := jwt.ParseToken(token)
			if err != nil {
				code = e.ErrorTokenCheck
			} else if time.Now().Unix() > claims.ExpiresAt {
				code = e.ErrorTokenTimeout
			}
			c.Set("uid", claims.Id)
		}
		if code != e.SUCCESS {
			c.JSON(http.StatusBadRequest, serializer.MsgResponse(code))
			c.Abort()
			return
		}
		c.Next()
	}
}
